<?php
/**
 * Date: 2018/6/25
 * Time: 14:51
 * Author: zeronlee
 */

namespace App\Http\Controllers\Backend\SysConfig;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\SysConfig\SysConfig;

/**
 * Class IndexController
 * @package App\Http\Controllers\Backend\SysConfig
 */
class IndexController extends Controller
{

    public function index (Request $request){

        //index set info
        $settingInfo = SysConfig::where('module','!=','')->where('setting','!=','')->get();
        $baseInfo = $emailInfo = $distributeInfo = [];
        foreach ($settingInfo as $item){
            switch ($item->module){
                case 'base':
                    $baseInfo = json_decode($item->setting,true);
                    break;
                case 'email':
                    $emailInfo = json_decode($item->setting,true);
                    break;
                case 'distribute':
                    $distributeInfo = json_decode($item->setting,true);
                    break;
            }
        }
        return view('backend.sysconfig.index', ['baseInfo'=>$baseInfo, 'emailInfo'=>$emailInfo, 'distributeInfo'=>$distributeInfo]);
    }

    public function set(Request $request){
        $sysConfig = new sysConfig();
        //validate
        switch (intval($request->type)){
            case 1:
                $data = $request->sysconfig['base'];
                $validator = $sysConfig->vlidateBase($data);
                break;
            case 2:
                $data = $request->sysconfig['email'];
                $validator = $sysConfig->vlidateEmail($data);
                break;
            case 3:
                $data = $request->sysconfig['distribute'];
                $validator = $sysConfig->vlidateDistribute($data);
                break;
            default:
                throw new \Exception('非法操作');

        }

        if ($validator->fails()) {
            return redirect('admin/configindex')
                ->withErrors($validator)
                ->with('type',$request->type)
                ->withInput();
        }
        //insert or update
        try{

            $sysConfig->setRow($request);
        }catch (\Exception $e){
            \Log::info($e->getMessage());
        }
        return redirect('/admin/configindex')->with('type',$request->type);
    }

}